package com.mj.listen3.链表;

/**
 * https://leetcode-cn.com/problems/add-two-numbers/
 */
public class _2_两数相加 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;

        // 创建虚拟头节点
        ListNode dummyHead = new ListNode(0);
        ListNode last = dummyHead;

        // 进位值
        int carry = 0;
        while (l1 != null || l2 != null) {
            // l1 或者 l2 谁遍历完了，谁的后续位置节点值就是0
            int v1 = 0;
            if (l1 != null) {
                v1 = l1.val;
                l1 = l1.next;
            }

            int v2 = 0;
            if (l2 != null) {
                v2 = l2.val;
                l2 = l2.next;
            }

            int sum = v1 + v2 + carry;

            // 求下一步节点相加时候的最新的进位
            carry = sum / 10;

            // sum = 12，新节点中存的值是2
            last.next = new ListNode(sum % 10);
            last = last.next;
        }

        // 最后carry > 0，还需要再添加一个节点
        if (carry > 0) {
            last.next = new ListNode(carry);
            last = last.next;
        }

        return dummyHead.next;
    }
}
